<?php
    namespace Admin\Controller;
	use Think\Controller;
	class carController extends Controller{
		protected $userId, $userName;
	    protected function isAuthorize(){
               $loginStatus=session('admin_online');
               if(!$loginStatus){
                  $this->redirect('index','',2,'not authirize');
				  return false;
                  exit();
                }
               $this->userId=session('id');
               $this->userName=session('email');
               $this->assign('userName',$this->userName);
               $this->assign('userId',$this->userId);			
			
		}
		
		public function addCar(){
			$this->isAuthorize();
			if(empty($_POST)){
				$this->display('addcar');
				return false;
			}
			$carObj= D('car');
			$carId=$carObj->addCar($_POST['name'],$_POST['price'],$_POST['number_of_people'],$_POST['number_of_baggage'],$_POST['car_operation'],$_POST['describe'],$_FILES['pic']);
			if($carId== false){
				echo $carObj->getLastError();
				return false;
			}
			$this->redirect('index/main','',2,'sucsses');
			
		}
		
		public function carList($page=1){
			$this->isAuthorize();
			$carToken=time();
			session('carToken',$carToken);
			$carObj= D('car');
			$limit=10;
			$carList=$carObj->getCarList($page,$limit);
			$carCount=$carObj->getCarCount();
			$pageObj=new \Admin\Model\PageModel($carCount,$page);
			$countPage=$pageObj->getCountPage($limit);
			$nextPage=$pageObj->getNextPage();
			$previousPage=$pageObj->getPreviousPage();
			$this->assign('nextPage',$nextPage);
			$this->assign('previousPage',$previousPage);
			$this->assign('countPage',$countPage);
			$this->assign('carCount',$carCount);
			$this->assign('carToken',$carToken);
			$this->assign('carList',$carList);
			$this->display('carList');
		}
		
		public function deleteCar($carId,$carToken){
			$this->isAuthorize();
			if($carToken !=session('carToken')){
				$this->redirect('carList','',2,'error token');
			}
			$carObj= D('car');
			$affectRow=$carObj->deleteCar($carId);
			if($affectRow==false){
				$this->redirect('carList','',2,$car->getLastError());
				return false;
			}
			$this->redirect('carList','',2,'sucsses');
		}
		
		public function updateCarInfo($carId=1){
			$this->isAuthorize();
			$carObj= D('car');
			if(empty($_POST)){
				$carInfo=$carObj->getCarById($carId);
				$this->assign('carInfo',$carInfo);
				$this->display('updateCar');
				return false;
			}
			$affectRow=$carObj->updateCar($_POST['car_id'],$_POST['name'],$_POST['price'],$_POST['number_of_people'],$_POST['number_of_baggage'],$_POST['car_operation'],$_POST['describe'],$_FILES['pic']);
			
			if($affectRow){
				$this->redirect('carList','',2,'sucsses');
				return true;
			}
			$this->redirect('carList','',20,$carObj->getLastError());
				return false;
			
			
		}
	}